import subprocess
from rich.console import Console
c = Console(color_system='256', style=None)
def run_cmd(command):
    """
    运行CMD命令并返回输出结果
    --注意--:
        该方法为内部指令,请勿调用!
    参数：
    command (str): 要执行的CMD命令

    返回：
    output (str): 命令执行的输出结果
    """
    try:
        result = subprocess.run(command, shell=True, capture_output=True, text=True)
        if result.returncode == 0:
            output = result.stdout.strip()
        else:
            output = result.stderr.strip()
    except Exception as e:
        output = str(e)

    return output
print("ATC(AdbToolCtrl) v:bate_1.0.0 successful!")
class AdbCtrl:
    def __init__(self):
        '''
        初始化adb
        '''
        run_cmd("adb devices")
        if "cannot" in run_cmd("adb root"):
            self.is_root = False
            self.is_connect = True
        elif "devices/emulators" in run_cmd("adb devices"):
            self.is_root = False
            self.is_connect = False
        else:
            self.is_root = True
            self.is_connect = True
    def loader_usb(self) -> str:
        '''
        初始化adb-检测usb
        '''
        return run_cmd("adb devices")
    def stater_shizuku(self) -> str:
        '''
        通过adb启动shizuku
        '''
        return run_cmd("adb shell sh /storage/emulated/0/Android/data/moe.shizuku.privileged.api/start.sh")
    def start_adb(self) -> str:
        '''
        启动adb
        '''
        return run_cmd("adb start-server")
    def stop_adb(self) -> str:
        '''
        杀死adb
        '''
        return run_cmd("adb kill-server")
    def restart_adb(self) -> str:
        a=AdbCtrl.start_adb(self)
        b=AdbCtrl.stop_adb(self)
        return a+"\n"+b
    def list_adb_package(self) -> str:
        return run_cmd("adb shell pm list package")
    def list_adb_package_s(self,find) -> str:
        return run_cmd("adb shell pm list packages "+find)
    def adb_install(self,apk) -> int:
        '''
        安装功能
        注意:安装系统自带实时rich输出,无返回值(固定0)!
        '''
        # 执行外部命令
        p = subprocess.Popen("adb install "+apk, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

        # 获取实时输出
        for line in iter(p.stdout.readline, b''):
            c.print(line.decode('utf-8').strip())
        # 等待命令执行完成
        p.wait()
        return 0
    def adb_uninstall(self,pack_name) -> int:
        '''
        卸载功能
        注意:卸载系统自带实时rich输出,无返回值(固定0)!
        '''
        # 执行外部命令
        p = subprocess.Popen("adb uninstall " + pack_name, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

        # 获取实时输出
        for line in iter(p.stdout.readline, b''):
            c.print(line.decode('utf-8').strip())
        # 等待命令执行完成
        p.wait()
        return 0
    def adb_uninstall_F(self, pack_name) -> int:
        c.print("[red]E:=-库级警告-=:[yellow]注意,该手段为强制卸载,有可能会出现系统损坏,是否确认执行[N,y]>")
        inp=input()
        if inp == "y" or inp == "Y":
            c.print("[red]E:=-库级警告-=:[yellow]注意,该手段为强制卸载,有可能会出现系统损坏,请再次确定是否执行[N,y]>")
            inp = input()
            if inp == "y" or inp == "Y":
                c.print("[red]P:开始执行强制删除!")
                #adb shell pm path com.xxx.xxx 查找apk包位置
                pack_path = (run_cmd("adb shell pm path "+pack_name).split(":"))[1]
                c.print("[red]正在挂载系统读写权限!")
                c.print(run_cmd("adb remount"))
                c.print("[green]挂载成功!")
                c.print("[red]正在删除包!")
                #adb shell rm /data/app/com.xxx.xxx-1/base.apk
                c.print(run_cmd("adb shell rm "+pack_path))
                c.print("[green]S:删除完成,是否现在重启设备?[Y,n]>")
                inp=input()
                if inp != "N" and inp != "n":
                    #adb reboot
                    c.print("[green]设备重启!")
                    c.print(run_cmd("adb reboot"))
                    c.print("[green]重启指令执行完成!")
    def adb_reboot(self) -> str:
        return run_cmd("adb reboot")
    def adb_log(self) -> str:
        return run_cmd("adb logcat")
    def adb_run_apk(self, pack_name) -> str:
        return run_cmd("adb shell am start "+pack_name)
    def adb_root(self):
        if self.is_root:
            return run_cmd("adb root")
        else:
            c.print("[red]E:[yellow]你的手机无法获取root权限,可能是没有root!")
    def adb_shell(self,cmd):
        return run_cmd("adb shell "+cmd)
    def adb_Ps(self):
        return run_cmd("adb shell ps")
    def adb_adbTool_kill_huawei_jiankang(self):
        return run_cmd("adb shell appops set com.huawei.parentcontrol SYSTEM_ALERT_WINDOW ignore")